
// node .\create_algorithm.js --path=SLM_20220225.json --clean=true
// node .\create_algorithm.js --path=SLM_20220225.json
const fs = require('fs');
const args = require('minimist')(process.argv.slice(2))

var jsonFilePath = './SLM_20220301.json';

const doneList = {
  'Perceptron':'lc',
  'DualFormPerceptron':'lc',
  'KNN':'lc',
  'KDTree':'lc',
};

if(args['path']){
   jsonFilePath = './SLM_20220301.json';
}

if(args['clean']){
  fs.readFile(`./${jsonFilePath}`, 'utf-8', (err, json)=>{
    if(err) console.log(err);
    const algorithms = JSON.parse(json).Algorithms;
    for(var key in algorithms){
      var id = algorithms[key].id.trim();
      fs.unlink(`./algorithms/${id}.js`, (err)=>{
        if(err) console.log(err);
      })
    }
  });
  fs.unlink(`./algorithms/AlgorithmImport.js`, (err)=>{
    if(err) console.log(err);
  })
  process.exit ();
}

console.log('生成算法类...')

fs.readFile('./template/AlgorithmTemplate.js', 'utf-8', function (err, template){
  if(err) console.log(err);

  fs.readFile(`./${jsonFilePath}`, 'utf-8', (err, json)=>{
    if(err) console.log(err);
    const algorithms = JSON.parse(json).Algorithms;
    for(var key in algorithms){
      var id = algorithms[key].id.trim();
      if(id in doneList) continue;
      const tmp = template.replace(/\$/g, id);
      // console.log(id, template);
      fs.writeFile(`./algorithms/${id}.js`, tmp, (err)=>{
        if(err) console.log(err);
      });
    }
    fs.readFile('./template/AlgorithmImportTemplate.js', 'utf-8', (err, impTemplate)=>{
      if(err) console.log(err);
      const st = impTemplate.indexOf('/*');
      const end = impTemplate.indexOf('*/');
      const sub = impTemplate.substring(st + 2, end);
      let tmp = impTemplate.substring(0, st);
      for(var key in algorithms){
        var id = algorithms[key].id.trim();
        id = id.replace(/\s+|-|\./g,'');
        tmp += sub.replace(/\$/g, id);
      }
      tmp += impTemplate.substring(end + 2);
      fs.writeFile(`./algorithms/AlgorithmImport.js`, tmp, (err)=>{
        if(err) console.log(err);
      });
    });
  });
})

console.log('生成成功.');